<template>
	<!-- #ifdef H5 -->
	<fui-sticky zIndex="999">
		<view style="width: 100vw;background-color: #fff;">
			<fui-nav-bar :title="'在线人数('+data.numTrue+')'">
			</fui-nav-bar>
		</view>
	</fui-sticky>
	<!-- #endif -->

	<!-- 聊天界面展示https://www.bilibili.com/video/BV1hT4y1P75N?p=22  搭建1和2 -->
	<view class="content">
		<!-- 聊天内容 -->
		<scroll-view class="chat" :refresher-enabled="data.isSX" :refresher-triggered="data.triggered"
			@refresherpulling="onPulling" @refresherrestore="onRestore" @refresherabort="onAbort"
			@refresherrefresh="onRefresh" scroll-y="true" scroll-with-animation="true" @scrolltolower="loadMoreMessages"
			:scroll-into-view="data.scrollToView">
			<view class="chat-main" :style="{paddingBottom:data.inputh+'px'}">
				<view class="chat-ls" v-for="(item,index) in data.msgData" :key="index" :id="'msg'+ index">
					<view class="chat-time" v-if="item.create_time != ''">{{changeTime(item.create_time)}}</view>
					<view class="msg-m msg-left" v-if="item.from__id!==userInfo._id">
						<image class="user-img" :src="item.from__avatar"></image>
						<view class="message" v-if="item.type == 'text'">
							<!-- 文字 -->
							<view class="msg-text" v-html="translateHtml(item.body)"
								@click="openLink(translateHtml(item.body))"></view>
						</view>
						<view class="message" v-if="item.type == 'image'" @tap="previewImg(item.body)">
							<!-- 图像 -->
							<image :src="item.body" class="msg-img" mode="widthFix"></image>
						</view>
					</view>
					<view class="msg-m msg-right" v-if="item.from__id==userInfo._id">
						<image class="user-img" :src="item.from__avatar"></image>
						<view class="message" v-if="item.type == 'text'">
							<view class="msg-text" v-html="translateHtml(item.body)"
								@click="openLink(translateHtml(item.body))"></view>
						</view>
						<view class="message" v-if="item.type == 'image'" @tap="previewImg(item.body)">
							<image :src="item.body" class="msg-img" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<submit @inputs="inputs" @heights="heights"></submit>
		<bottomPop></bottomPop>
	</view>
</template>

<script setup>
	function translateHtml(msg) {
		var reg = /((http|https):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])/g;
		var textR = msg.replace(reg, "<text style='color: #00a0e9;width: 360px;display: inline;'>$1</text>");
		return textR;
	}
	import { LoginStore } from "@/store/modules/login.js";
	const imApi = uniCloud.importObject('qc-im', {
		customUI: true
	})
	import dateTime from '@/utils/dateTime.js';
	import submit from '@/components/submit/submit.vue';
	import bottomPop from '@/components/bottomPop.vue'
	import { ref, reactive, computed, nextTick } from 'vue'
	import { onLoad, onReachBottom, onPageScroll, onPullDownRefresh } from "@dcloudio/uni-app";
	const userInfo = computed(() => (LoginStore()?.userInfo))
	const data = reactive({
		msgData: [],
		scrollToView: '',
		oldTime: new Date(),
		inputh: '50',
		pageNum: 1, // 当前页码
		pageSize: 10, // 每页显示条目数量
		totalPage: 100, // 总共页面数
		numTrue: 0,
		triggered: false, //是否下拉成功
		_freshing: false,
		isSX: true
	})
	onLoad(async () => {
		data.isSX = true
		data.triggered = true;
		data._freshing = false;
		const res = await imApi.getuserID()
		data.numTrue = res.data
		uni.setNavigationBarTitle({
			title: `在线人数(${res.data})`
		});
		uni.$on('uniIm', async (e) => {
			if (e.from__id !== userInfo.value._id) {
				data.msgData.push({
					from__id: e.from__id,
					body: e.data,
					from__avatar: e.avatar,
					type: e.type,
					create_time: e.create_time
				})
				goBottom()
			}
		})
		await init()
		await goBottom()
	})
	const init = async () => {
		const res = await imApi.getGroupMsg({ pageNum: data.pageNum, pageSize: data.pageSize })
		if (res.data.length !== 0) {
			data.msgData = [...res.data.reverse(), ...data.msgData];
			data.totalPage = res.count
		}
	}
	//跳转链接
	const openLink = (e) => {
		var pattern = /<[^>]+>/g;
		var text = e.replace(pattern, "");
		uni.setClipboardData({
			data: text, //要被复制的内容
			success: () => { //复制成功的回调函数
				uni.showToast({ //提示
					title: '复制成功'
				})
			}
		});
	}
	//下拉加载分页
	const onPulling = (e) => {

	}
	const onRefresh = async () => {
		if (data._freshing) return;
		data._freshing = true;
		if (data.totalPage / data.pageSize < data.pageNum) {
			data.isSX = false
		} else {
			data.pageNum++
			await init()
			data.triggered = false;
			data._freshing = false;
		}
	}
	const onRestore = () => {
		data.triggered = 'restore'; // 需要重置
	}
	const onAbort = () => {

	}
	const changeTime = (date) => {
		return dateTime.dateTime1(date);
	}
	// 进行图片的预览
	const previewImg = (e) => {
		// 预览图片
		uni.previewImage({
			current: 1,
			urls: [e],
			longPressActions: {
				itemList: ['保存图片'],
				success: function(res) {

					if (res.index == 0) {
						plus.nativeUI.closePreviewImage();
						//保存到相册
						uni.saveImageToPhotosAlbum({
							filePath: e,
							success: function() {
								uni.showToast({
									title: '成功保存到系统相册中',
									icon: 'none',
									duration: 2000
								});
							}
						});
					}

				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	}
	//接受输入内容
	const inputs = async (e) => {
		console.log(e);
		//时间间隔处理
		let params = {
			from__id: userInfo?.value?._id,
			body: e.message,
			from__nickname: userInfo?.value?.nickname,
			from__avatar: userInfo?.value?.avatar,
			type: e.type,
			create_time: new Date()
		};
		// 发送给服务器消息
		data.msgData.push(params);

		const res = await imApi.sendMsg({
			user_id: userInfo?.value?._id,
			type: e.type,
			body: e.message
		})

		// 跳转到最后一条数据 与前面的:id进行对照
		nextTick(function() {
			data.scrollToView = 'msg' + (data.msgData.length - 1)
		})
	}
	//输入框高度
	const heights = (e) => {
		data.inputh = e;
		goBottom();
	}
	// 滚动到底部
	const goBottom = () => {
		data.scrollToView = '';
		nextTick(function() {
			data.scrollToView = 'msg' + (data.msgData.length - 1)
		})
	}
</script>

<style lang="scss">
	page {
		height: 100%;
	}

	.content {
		height: 100%;
		background-color: rgba(244, 244, 244, 1);
	}

	.chat {
		height: 95%;

		.chat-main {
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-top: 20rpx;
			padding-bottom: 150rpx; //获取动态高度
			display: flex;
			flex-direction: column;
		}

		.chat-ls {
			.chat-time {
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				line-height: 34rpx;
				padding: 10rpx 0rpx;
				text-align: center;
			}

			.msg-m {
				display: flex;
				padding: 20rpx 0;

				.user-img {
					flex: none;
					width: 80rpx;
					height: 80rpx;
					border-radius: 20rpx;
				}

				.message {
					flex: none;
					max-width: 480rpx;
				}

				.msg-text {
					word-wrap: break-word;
					font-size: 32rpx;
					color: rgba(39, 40, 50, 1);
					line-height: 44rpx;
					padding: 18rpx 24rpx;
				}

				.msg-img {
					max-width: 300rpx;
					border-radius: 20rpx;
				}

				.msg-map {
					background: #fff;
					width: 464rpx;
					height: 284rpx;
					overflow: hidden;

					.map-name {
						font-size: 32rpx;
						color: rgba(39, 40, 50, 1);
						line-height: 44rpx;
						padding: 18rpx 24rpx 0 24rpx;
						//下面四行是单行文字的样式
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 1;
						overflow: hidden;
					}

					.map-address {
						font-size: 24rpx;
						color: rgba(39, 40, 50, 0.4);
						padding: 0 24rpx;
						//下面四行是单行文字的样式
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 1;
						overflow: hidden;
					}

					.map {
						padding-top: 8rpx;
						width: 464rpx;
						height: 190rpx;
					}
				}

				.voice {
					// width: 200rpx;
					min-width: 100rpx;
					max-width: 400rpx;
				}

				.voice-img {
					width: 28rpx;
					height: 36rpx;
				}
			}

			.msg-left {
				flex-direction: row;

				.msg-text {
					margin-left: 16rpx;
					background-color: #fff;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
				}

				.ms-img {
					margin-left: 16rpx;
				}

				.msh-map {
					margin-left: 16rpx;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
				}

				.voice {
					text-align: right;

				}

				.voice-img {
					float: left;
					transform: rotate(180deg);
					width: 28rpx;
					height: 36rpx;
					padding-bottom: 4rpx;
				}
			}

			.msg-right {
				flex-direction: row-reverse;

				.msg-text {
					margin-right: 16rpx;
					background-color: rgba(255, 228, 49, 0.8);
					border-radius: 20rpx 0rpx 20rpx 20rpx;
				}

				.ms-img {
					margin-right: 16rpx;
				}

				.msh-map {
					margin-left: 16rpx;
					border-radius: 20rpx 0rpx 20rpx 20rpx;
				}

				.voice {
					text-align: left;

				}

				.voice-img {
					float: right;
					padding: 4rpx;
					width: 28rpx;
					height: 36rpx;
				}
			}
		}
	}
</style>